package com.framework.auth.config;

import com.framework.auth.translator.AuthenticationResultHandler;
import com.framework.auth.util.AuthenticationHandlerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class SecurityConfig {
    private static final String CUSTOM_LOGIN_PAGE_URI = "/login";

    @Autowired
    private AuthenticationResultHandler errorHandler;

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                // 配置放行的请求
                .antMatchers("/oauth2/**","/login").permitAll()
                // 其他任何请求都需要认证
                .anyRequest().authenticated()
        )
                // 设置登录表单页面（这个是Spring Security的登录，有独立的表需要改造）
                .formLogin(formLoginConfigurer -> formLoginConfigurer
                        .loginPage(CUSTOM_LOGIN_PAGE_URI))
                .exceptionHandling(configurer -> {
                    configurer.accessDeniedHandler(errorHandler);
                })
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 此处会过滤token是否有效， 不配做 jwt， token不会过滤
                .and().oauth2ResourceServer().jwt();

        SecurityFilterChain chain = http.build();
        AuthenticationHandlerUtils.resetErrorHandler(chain, errorHandler);

        return chain;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new ExtendPasswordEncoder();
    }
}
